<?php
/**
 * Created by PhpStorm.
 * User: WangXiaoHong
 * Date: 15-10-27
 * Time: 下午4:02
 */

$pdo = new PDO('mysql:dbname=myuu_test;host=127.0.0.1;port=3307', 'admin', 'adm*753951');
$pdo->exec('SET NAMES "UTF8"');
$data_now = date('Y-m-d H:i:s');
use \PFT\Db;
include_once '/var/www/html/new/d/module/common/Db.class.php';
$dbConf = include_once '/var/www/html/new/d/module/common/db.conf.php';// 远端服务器配置信息
Db::Conf($dbConf['localhost']);
include  '/var/www/html/new/d/common/func.inc.php';
include  '/var/www/html/new/d/api/ProductApi.php';
$request_data = file_get_contents("php://input");
if (empty($request_data)) {
    exit('empty request data');
}
//TODO::Let's log it first.
ProductApi::writeLog( $data_now .'|'.$request_data, 'request_data');
$post_data = json_decode($request_data);
foreach($post_data as $origin_id=>$json_array){
    $body       = $json_array->land;
    $product    = new ProductApi($pdo);
    //TODO::判断是更新还是插入
    $remote_id = (int)$json_array->tickets[0]->id;//对方平台产品id
    ProductApi::$remoteId = $remote_id;//设置对方平台产品ID
    $account   = (int)$body->aid;//id=>50618
    //账户验证,并获取供应商的id，即pft_member表的ID
    $apply_did = aid($account);
    if(empty($apply_did))exit('{"code":"无此供应商"}');

    $chkRet = $product->ChkUpdateOrInsert($account, $remote_id);
    $tid  = empty($chkRet)?0:1;
    $mode = empty($chkRet)?0:1;
    //TODO::写数据到uu_land表
    $landInfo   = array();//uu_land表数据
    $extInfo    = array();
    $ticketInfo = array();//uu_jq_ticket表数据

    $landInfo['title']    = safetxt((string)$body->product_name);
    $landInfo['tel']      = (string)$body->tel;
    $landInfo['jtype']    = (string)$body->product_level;
    $landInfo['opentime'] = (string)$body->opentime;

    $ptype = (string)$body->product_type;
    if (!in_array($ptype, array('A','B','C','F'))) {
        ProductApi::Response('105');
    }
    if ( $ptype== 'B') {
        if (empty($body->start_city) || empty($body->end_city)) {
            ProductApi::Response('126');//126：出发地/目的地 产品类型为线路时，必填
        }
        $extInfo['startplace']      = (string)$body->start_city;//
        $extInfo['endplace']        = (string)$body->end_city;//

        $landInfo['runtime'] = (string)$body->start_city . '|'.(string)$body->end_city;
        $new_ass = array();
        foreach ($body->ass_stations->ass_station as $ass_station) {
            $new_ass[] = "集合地点:" . $ass_station->assembling_place
                . ",集合时间:" . $ass_station->assembling_time
                . ",导游手机:" . $ass_station->guide_telphone;
        }
        if (!count($new_ass)) {
            ProductApi::Response('128');//126：出发地/目的地 产品类型为线路时，必填
        }
        $extInfo['ass_station']  = serialize($new_ass);
        if (empty($body->journey_days) || $body->journey_days<0) {
            ProductApi::Response('127');//127：游玩天数 产品类型为线路时，必填
        }
        $extInfo['rdays']        = (int)$body->journey_days;
        $series_model            = explode('|', (string)$body->series_model);
        $extInfo['series_model'] = $series_model[0] .'{fck_date}' . $series_model[1];
    }
    elseif($ptype == 'F') {
        //套票[{"pid":"18","num":"1","lid":"16","aid":"4"}]
        $packages = array();
        $pft_pids = array();
        foreach ($body->include_ticket->ticket as $ticket) {
            $packages[(int)$ticket->id]['num'] = (int)$ticket->num ;
        }
        if (!count($packages)) {
            ProductApi::Response('101');
        }
        $sql_get_pft_pid = "SELECT pid,remoteid FROM get_Product_Fromt_Lib WHERE remoteid IN(".implode(',', $pids).")";
        $stmt = $pdo->prepare($sql_get_pft_pid);
        $stmt->execute();
        while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
            $pft_pids[] = $row['pid'];
            $packages[$row['remoteid']]['pid'] = $row['pid'];
        }
        $stmt = null;
        unset($stmt);
        if (!count($pft_pids)) {
            ProductApi::Response('102');
        }
        $sql_get_pft_lid = "SELECT contact_id,apply_did FROM uu_products WHERE id IN(".implode(',', $pft_pids).")";
        $stmt = $pdo->prepare($sql_get_pft_pid);
        $stmt->execute();
        while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
            $packages[$row['remoteid']]['lid'] = $row['contact_id'];
            $packages[$row['remoteid']]['aid'] = $row['apply_did'];
        }
        $landInfo['attribute'] = json_encode(array_values($packages));
        $stmt = null;
        unset($stmt);
        unset($packages);
        unset($pft_pids);
    }
//要特殊处理
    if (!empty($body->city)) {
        $areaArr = explode('|', (string)$body->city);
        $sql = "SELECT area_id FROM uu_area WHERE area_name LIKE '%{$areaArr[0]}%' LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $province = $stmt->fetchColumn(0);
        $sql = "SELECT area_id FROM uu_area WHERE area_name LIKE '%{$areaArr[1]}%' LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $city = $stmt->fetchColumn(0);
        $landInfo['area']      = "{$province}|{$city}"."|0";
        $sql_area  ="select n_code from pft_area_code_concat where s_code='{$landInfo['area']}' LIMIT 1";
        $stmt = $pdo->prepare($sql_area);
        $stmt->execute();
        /*地区编号*/
        $landInfo['areacode'] = $stmt->fetchColumn(0);
    }
    if (empty($body->address)) {
        ProductApi::Response('125');//详细地址为空
    }
    $landInfo['address']   = safetxt( (string)$body->address);
    $landInfo['jqts']      = safetxt( (string)$body->notice);
    $landInfo['bhjq']      = safehtml( (string)$body->details );
    $landInfo['jtzn']      = safetxt( (string)$body->traffic);
    $landInfo['imgpath']   = safetxt( (string)$body->imgpath);
    $landInfo['addtime']   = ProductApi::now();
    $landInfo['p_type']    = $ptype;
    $landInfo['p_type']    = $ptype;
    $landInfo['lng_lat_pos']    = (!empty($body->lng) && !empty($body->lat)) ?  ($body->lng.','.$body->lat) :'';
    $landInfo['delaytime'] = safetxt( (string)$body->delaytime);
    $landInfo['status']    = 1;
    $landInfo['apply_did'] = $apply_did;

//TODO::写数据到uu_jq_ticket表
    $Y_m_d = date('Y-m-d');
    $landInsertRes   = $product->AddProduct($landInfo);
    if ($landInsertRes===1) {
        ProductApi::Response('118');
    }
    if ($landInsertRes===2) {
        ProductApi::Response('119');
    }
    if ($landInsertRes===3) {
        ProductApi::Response('117');
    }
    if ($landInsertRes===4) {
        ProductApi::Response('114');
    }

    $lid = $landInsertRes['lastid'];

    foreach ($json_array->tickets as $tkt) {
        $ticketInfo['title']             = safetxt( (string)$tkt->ticket_name );
        if (!$ticketInfo['title']) {
            ProductApi::Response('103');
        }
        $ticketInfo['tprice']            = (float)$tkt->market_price;
        $ticketInfo['getaddr']           = safetxt( (string)$tkt->get_ticket_info );

        if (!$ticketInfo['getaddr']) {
            ProductApi::Response('104');//104:取票信息不能为空
        }
        if ( !in_array((int)$tkt->payment_type, array(0,1)) ) {
            ProductApi::Response('108');
        }
        $ticketInfo['pay']               = $tkt->payment_type;
        $ticketInfo['storage']           = $tkt->total_storage;
        $ticketInfo['cancel_auto_onMin'] = 120;
        $ticketInfo['uuid']              = $tkt->id;

        if ( $ptype!='F' && !in_array((int)$tkt->use_delay_type, array('0','1','2','3')) ) {
            ProductApi::Response('109');
        }
        $ticketInfo['delaytype']         = (int)$tkt->use_delay_type;
        if ( ($tkt->use_delay_type==1 || $tkt->use_delay_type==2) && !$tkt->use_delay_days) {
            ProductApi::Response('110');
        }
        $ticketInfo['delaydays']         = (int)$tkt->use_delay_days;
        if ($tkt->use_delay_type==3 && !$tkt->use_deadline) {
            ProductApi::Response('111');
        }
        $ticketInfo['order_end']         = $tkt->price_array->end_date;
        $ticketInfo['order_start']       = $tkt->price_array->start_date;
        $ticketInfo['ddays']             = (int)$tkt->book_early_days;
        $recharge = (float)$tkt->refundcharge;
        if (!is_numeric($recharge) || $recharge>100) {
            ProductApi::Response('112');
        }
        $ticketInfo['reb']               = (float)$tkt->refundcharge;//退款手续费(%)
        $ticketInfo['buy_limit_low']     = (int)$tkt->buy_min_num;
        $ticketInfo['buy_limit_up']      = (int)$tkt->pribuy_max_num;
        $ticketInfo['apply_did']         = $apply_did;
        $ticketInfo['cancel_auto_onMin'] = (int)$tkt->auto_cancel_minute;//自动取消时间

        $ticketInfo['Mdetails']          = 1;//接口进来的这个字段固定为1
        $ticketInfo['Mpath']             = (string)$tkt->Mpath;
        $ticketInfo['sourceT']           = (int)$tkt->sourceT;
        //TODO::写数据到票类属性扩展表

        $extInfo['dhour']           = $tkt->book_deadline;//提前下单截止日具体时间

        $extInfo['v_ID_support']    = (int)$tkt->idcard_verify;//提前下单截止日具体时间
        if ( !empty($tkt->verify_start_time) ) {

            if (empty($tkt->verify_end_time)) {
                ProductApi::Response('129');//验证时间错误，必须设置截止验证时间。
            }
            $extInfo['v_time_limit']= (string)$tkt->verify_start_time . '|'
                . (string)$tkt->verify_end_time;
        }

        $priceArr = array();
        if (!count($tkt->price_array)) {
            ProductApi::Response('113');
        }

//        foreach ( $tkt->price_array  as $price) {
        if (empty($tkt->price_array->start_date) || empty($tkt->price_array->end_date)) {
            ProductApi::Response('121');//121:价格有效日期为空
        }
        $enddate = $tkt->price_array->end_date;
//        if($enddate < $Y_m_d) continue;//过滤今天之前的价格

        if ($tkt->price_array->retail_price<$tkt->price_array->supply_price) {
            ProductApi::Response('120');//120：零售价必须大于供货价
        }

        if (empty($tkt->price_array->valid_week)) {
            $ondays = '0,1,2,3,4,5,6';
        }
        else {
            $ondays_arr = explode(',', $tkt->price_array->valid_week);
            foreach ($ondays_arr as $week) {
                if ($week > 7 || $week <0) {
                    ProductApi::Response('130');//130：价格有效星期格式错误
                }
            }
        }
        $price = array(
            'price_id'   => (int)$tkt->price_array->price_id,
            'start_date' => (string)$tkt->price_array->start_date,
            'end_data'   => $enddate,
            'pg'         => (int)$tkt->price_array->supply_price,
            'pl'         => (int)$tkt->price_array->retail_price,
            'ondays'     => (string)$tkt->price_array->valid_week,
            'ptype'      => (int)$tkt->price_array->ptype,
            'storage'    => (int)$tkt->price_array->storage,
        );
        $ticketInfo['landid']       = $landInsertRes['lastid'];
        $ticketInfo['apply_did']    = $apply_did;
        $ticketInsertRet = $product->SaveTicket($ticketInfo);//写入uu_jq_ticket表
        if ($ticketInsertRet===false) {
            ProductApi::Response('115');//保存票类属性失败
        }

        if ($chkRet===false) {
            if ($ticketInsertRet===false) {
                ProductApi::Response('115');//保存票类属性失败
            }

            $pid = $ticketInsertRet['pid'];
            //TODO::写数据到票类属性扩展表
            $extInfo['pid']         = $pid;
            $extInfo['tid']         = $ticketInsertRet['lastid'];
            $extInfo['lid']         = $landInsertRes['lastid'];
            $extInfo['sendVoucher'] = 1;
            $extInfo['tourist_info']= 1;
            $ticket_ext = $product->ProductExt($extInfo);
            if ($ticket_ext === false ) {
                ProductApi::Response('116');
            }
            //添加价格
            $priceRes  = ProductApi::soap()->In_Dynamic_Price($pid,
                $price['start_date'],$price['end_data'],
                $price['pg'], $price['pl'], $price['ptype'], $mode,
                $price['price_id'], '', $price['ondays'], $price['storage']);
            if ($priceRes==142) {
                ProductApi::Response('122');//122：一个票种多个价格有效期日期重叠
            }
            elseif ($priceRes!=100) {
                ProductApi::writeLog(ProductApi::now()."|价格插入失败.返回{$priceRes}",
                    'price.err');
                ProductApi::Response('100');
            }
            //最后更新产品表状态(uu_products.apply_limit=1)
            $product->SetTicketState($pid, 1);
            $landUpdateRes   = $product->InsertProduct_Fromt($account, $ticketInsertRet['pid'],$ticketInfo['uuid']);
            //TODO::写数据到uu_jq_ticket表
        }
    elseif (is_array($chkRet)) {
        //更新
        $handlerMode = 1;
        $landUpdateRes   = $product->UpdateScenery($landInfo, $chkRet['lid']);
        if ($landUpdateRes === false) {
            ProductApi::Response('114');//114：保存产品属性失败

        }
        $lid = $chkRet['lid'];
        $ticketInfo['landid']       = $chkRet['lid'];
        $ticketInsertRet = $product->SaveTicket($ticketInfo, $chkRet['tid']);

        if ($ticketInsertRet === false) {
            ProductApi::Response('115');
        }
        $pid = $ticketInsertRet['pid'];
        $tid = $ticketInsertRet['lastid'];

        $ticket_ext = $product->ProductExt($extInfo, $chkRet['lf_id']);
        if ($ticket_ext === false) {
            ProductApi::Response('116');
        }
        //TODO::添加价格
        foreach ($priceArr as $price) {
            //TODO::判定这个价格是否已经写入到数据库
            $sql_get_priceid = <<<SQL
SELECT id FROM uu_product_price WHERE pid=$pid AND rid={$price['price_id']} LIMIT 1
SQL;
            $stmt = $pdo->prepare($sql_get_priceid);
            $stmt->execute();
            $price_id = $stmt->fetchColumn(0);
            if ($price_id) {
                $mode = 1;
                $rid = $price_id;
            }
            else {
                $mode = 0;
                $rid  = 0;
            }
            $priceRes  = ProductApi::soap()->In_Dynamic_Price_Merge($pid, $price['start_date'],$price['end_data'],
                $price['pg'], $price['pl'], $price['ptype'], $mode, $rid, '', $price['ondays'], $price['storage']);
            if ($priceRes!=100) {
                ProductApi::writeLog(ProductApi::now()."|价格插入失败.返回{$priceRes}",
                    'price.err');
                ProductApi::Response('100');
            }
        }
    }

    ProductApi::Response(200, array(
            'code'      => 200,
            'mode'      => $handlerMode,
            'pid'       => $pid,
            'lid'       => $lid,
            'remote_id' => $remote_id,
        )
    );
}
}
function aid($account){
    $sqlPwd = "select id FROM pft_member WHERE account=? LIMIT 1";
    $stmt = Db::Connect()->prepare($sqlPwd);
    $stmt->execute(array($account));
    $apply_did  = $stmt->fetchColumn();
    return $apply_did;
}
